<template>
  <div class="affairBaseInfo">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="事项名称" prop="serviceName">
        <el-input
          v-model="queryParams.serviceName"
          placeholder="请输入事项名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="事项编码" prop="serviceCode">
        <el-input
          v-model="queryParams.serviceCode"
          placeholder="请输入事项编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="事项类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择事项类型" clearable>
          <el-option
            v-for="item in navTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型" prop="businessType">
        <el-select v-model="queryParams.businessType" placeholder="请选择业务类型" clearable>
          <el-option
            v-for="item in businessTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['items:service:add']"
        >新增自定义事项
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-connection"
          size="mini"
          @click="handleAssociateService"
          v-hasPermi="['items:service:associate']"
        >关联事项系统事项
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['items:service:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['items:service:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['items:service:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList()"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="事项编码" width="190" align="center" prop="serviceCode"/>
      <el-table-column label="事项名称" align="center" prop="serviceName"/>
      <el-table-column label="事项类型" align="center" prop="type">
        <template slot-scope="props">
          <div @click="getMatterType(props)" :class="props.row.type === 12 ? 'provinceWide' : ''">
            {{ queryDictLabel(navTypeOptions, props.row.type) }}
          </div>
        </template>
      </el-table-column>
<!--      <el-table-column label="事项路由地址" align="center" prop="serviceUrl"/>-->
      <el-table-column label="事项图标" align="center" width="80" prop="icon">
        <template slot-scope="scope">
          <el-popover
            v-if="scope.row.icon"
            placement="top-start"
            width="300"
            trigger="hover"
          >
            <p> {{ scope.row.icon }}</p>
            <el-button
              size="small"
              type="primary"
              icon="el-icon-document-copy"
              @click="copyImageUrl(scope.row.icon)"
            >
              复制图片URL
            </el-button>

            <template slot="reference">
              <el-image
                fit="contain"
                :src="scope.row.icon"
                :preview-src-list="[scope.row.icon]"
                ref="elImage"
                style="width: 60px; height:60px;"
              />
            </template>
          </el-popover>
          <template v-else>无</template>
        </template>
      </el-table-column>

      <el-table-column label="是否启用" align="center">
        <template slot-scope="props">
          {{ queryDictLabel(isEnableOptions, props.row.enable) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row,scope.index)"
            v-hasPermi="['items:service:query']"
          >详细
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['items:service:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['items:service:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList()"
    />

    <!-- 添加或修改自定义事项对话框 -->
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="openEditDialog"
      width="1200px"
      append-to-body
      v-if="openEditDialog"
    >
      <div class="dialog-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="事项编码" prop="serviceCode" v-if="form.serviceCode">
                <el-input v-model="form.serviceCode" placeholder="请输入事项编码" :disabled="true"/>
              </el-form-item>
              <el-form-item label="事项名称" prop="serviceName">
                <el-input v-model="form.serviceName" placeholder="请输入事项名称" :disabled="form.id && form.serviceType===1"/>
              </el-form-item>
              <el-form-item label="事项描述" prop="serviceAbstract">
                <el-input v-model="form.serviceAbstract" placeholder="请输入事项描述"/>
              </el-form-item>
              <el-form-item label="事项图标" prop="icon">
                <template>
                  <el-input v-model="form.icon" clearable placeholder="请输入事项图标图片URL或者上传图片"/>
                  <UFileUpload
                    style="margin-top: 20px"
                    :value="form.icon"
                    :limit="1"
                    :fileSize="2"
                    @input="imageUploadSuccess"
                  />
                </template>
              </el-form-item>

            </el-col>
            <el-col :span="12">
              <el-form-item label="事项类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择事项类型" @change="handleServiceTypeChange">
                  <el-option
                    v-for="item in navTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <!--查询类事项才展示-->
              <el-form-item label="登录账号类型" prop="personType" v-if="form.type === 3 || form.type === 4">
                <el-select v-model="form.personType" placeholder="请选择登录账号类型">
                  <el-option
                    v-for="item in loginAccountTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="部门名称" prop="deptName" v-if="form.type === 3 || form.type === 4">
                <el-input v-model="form.deptName" placeholder="请输入部门名称"/>
              </el-form-item>
              <el-form-item label="入参配置" prop="serviceParam" v-if="form.type === 3 || form.type === 4">
                <el-input v-model="form.serviceParam" placeholder="用于一些使用同一模板、接口开发的事项，配置不同入参"/>
              </el-form-item>

              <el-form-item label="业务类型" prop="businessType">
                <el-select v-model="form.businessType" placeholder="请选择业务类型" @change="handleBusinessTypeChange">
                  <el-option
                    v-for="item in businessTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="生成PDF配置" prop="stamp" v-if="(form.type === 3 || form.type === 4) && form.businessType === 2">
                <el-select v-model="form.stamp" placeholder="请选择打印时生成PDF配置">
                  <el-option
                    v-for="item in printFooterOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item prop="serviceUrl" v-if="showServiceUrl">
               <span slot="label">
                <el-tooltip content="跳转页面的路由地址，如：`/site/step`，如果是外链需要以`http(s)://`开头" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                路由地址
              </span>
                <el-input v-model="form.serviceUrl" placeholder="请输入访问的路由地址"/>
              </el-form-item>

              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注（事项右上角标签）"/>
              </el-form-item>

              <el-form-item label="是否启用" prop="enable">
                <el-select v-model="form.enable" placeholder="请选择是否启用">
                  <el-option
                    v-for="item in isEnableOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24" v-show="showStepConfig" >
              <el-form-item label="事项步骤配置" prop="steps">
                <u-draggable-transfer
                  :sourceList="stepsList"
                  :checkKeys.sync="selectedStepIds"
                  ref="draggable"
                />
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 关联事项 -->
    <el-dialog
      :visible.sync="openAssociateServiceDialog"
      width="1200px"
      title="关联事项系统事项"
      append-to-body
      :close-on-click-modal="false"
      @close="closeAssociateServiceDialogCallback"
      class="custom-dialog"
    >
      <template>
        <div v-loading="associateServiceDialogLoading">

          <div style="margin-bottom: 20px">
            <el-input
              v-model="associateServiceQueryParams.serviceName"
              placeholder="请输入事项名称"
              clearable
              size="small"
              @keyup.enter.native="handleAssociateServiceSearch"
              style="width: 300px; margin-right: 10px"
            />
            <el-input
              v-model="associateServiceQueryParams.deptName"
              placeholder="请输入部门名称"
              clearable
              size="small"
              @keyup.enter.native="handleAssociateServiceSearch"
              style="width: 300px; margin-right: 10px"
            />
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleAssociateServiceSearch">搜索
            </el-button>
          </div>

          <el-table
            ref="associateServiceTable"
            max-height="500px"
            :data="associateServiceList"
            @selection-change="handleAssociateServiceSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="事项编码" width="190" align="center" prop="serviceCode"/>
            <el-table-column label="事项名称" align="center" prop="serviceName"/>
            <el-table-column label="事项图标" align="center">
              <template slot-scope="props">
                <el-input v-model="props.row.icon" placeholder="请输入事项图标URL"/>
              </template>
            </el-table-column>
            <el-table-column label="事项类型" align="center" width="180">
              <template slot-scope="props">
                <el-select v-model="props.row.type" placeholder="请选择">
                  <el-option
                    v-for="item in navTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="业务类型" align="center">
              <template slot-scope="props">
                <el-select v-model="props.row.businessType" placeholder="请选择业务类型">
                  <el-option
                    v-for="item in businessTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="是否启用" align="center" width="120">
              <template slot-scope="props">
                <el-select v-model="props.row.enable" placeholder="请选择">
                  <el-option
                    v-for="item in isEnableOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <!-- <div
               v-if="!selectedAssociateServiceInfoIsValid"
               class="clickMask"
               @click="showRowInfoIncompleteTip('换页')"
             /> -->
            <pagination
              v-show="associateServiceListTotal>0"
              :total="associateServiceListTotal"
              layout="total, prev, pager, next, jumper"
              :page.sync="associateServiceQueryParams.pageNum"
              :limit.sync="associateServiceQueryParams.pageSize"
              @pagination="handlePageChange"
            />
            <!--:disabled="!selectedAssociateServiceInfoIsValid"-->
          </div>
        </div>
      </template>

      <div slot="footer" class="dialog-footer">
        <div class="tip">
          注意：需要将当前页已选中的事项信息补充完整，才可进行换页 （可选勾选多页多个事项一次性添加）
        </div>
        <el-button
          type="primary"
          @click="handleConfirmAssociateService">
          确定关联
        </el-button>

        <el-button @click="openAssociateServiceDialog = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 事项详细信息 -->
    <el-dialog
      title="事项详细"
      :visible.sync="openDetailInfoDialog"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="detailInfoForm" label-width="130px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="事项编码：">{{ detailInfoForm.serviceCode }}</el-form-item>
            <el-form-item label="事项名称：">{{ detailInfoForm.serviceName }}</el-form-item>

            <el-form-item label="事项描述：">{{ detailInfoForm.serviceAbstract }}</el-form-item>
            <el-form-item label="事项图标：">
              <template>
                <el-popover
                  v-if="detailInfoForm.icon"
                  placement="top-start"
                  width="300"
                  trigger="hover"
                >
                  <p> {{ detailInfoForm.icon }}</p>
                  <el-button
                    size="small"
                    type="primary"
                    icon="el-icon-document-copy"
                    @click="copyImageUrl(detailInfoForm.icon)"
                  >
                    复制图片URL

                  </el-button>
                  <template slot="reference">
                    <el-image
                      fit="contain"
                      :src="detailInfoForm.icon"
                      :preview-src-list="[detailInfoForm.icon]"
                      ref="elImage"
                      style="width: 60px; height:60px;"
                    />
                  </template>
                </el-popover>
                <template v-else>无</template>
              </template>
            </el-form-item>
            <el-form-item label="路由地址：">{{ detailInfoForm.serviceUrl }}</el-form-item>
            <el-form-item label="备注：">{{ detailInfoForm.remark }}</el-form-item>
            <el-form-item label="创建人：">{{ detailInfoForm.createBy }}</el-form-item>
            <el-form-item label="创建时间：">{{ detailInfoForm.createTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事项类型：">
              {{ queryDictLabel(navTypeOptions, detailInfoForm.type) }}
            </el-form-item>

            <el-form-item v-if="detailInfoForm.type === 3 || detailInfoForm.type === 4" label="登录账号类型：">
              {{ queryDictLabel(loginAccountTypeOptions, detailInfoForm.personType) }}
            </el-form-item>

            <el-form-item label="部门名称：">{{ detailInfoForm.deptName }}</el-form-item>
            <el-form-item label="入参配置：">{{ detailInfoForm.serviceParam }}</el-form-item>

            <el-form-item label="业务类型：">
              {{ queryDictLabel(businessTypeOptions, detailInfoForm.businessType) }}
            </el-form-item>

            <el-form-item v-if="(detailInfoForm.type === 3 || detailInfoForm.type === 4) && detailInfoForm.businessType === 2" label="生成PDF配置：">
              {{ queryDictLabel(printFooterOption, detailInfoForm.stamp) }}
            </el-form-item>
            <el-form-item label="是否启用：">
              {{ queryDictLabel(isEnableOptions, detailInfoForm.enable) }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openDetailInfoDialog = false">关 闭</el-button>
      </div>
    </el-dialog>

<!--    全省通办事项关联-->
    <el-dialog
      :visible.sync="openAllMatterDialog"
      width="1300px"
      append-to-body
      :close-on-click-modal="true"
      @close="closeAllMatterDialog"
      class="custom-dialog"
    >
      <template>
        <div style="font-size: 18px;color: black">事项编码: {{ this.proServiceCode }} - 事项名称: {{ this.proServiceName }}</div>
      </template>
        <div class="bigDiv">
          <div v-loading="AllMatterLoading" class="div1">
            <div style="margin: 20px 0 20px 20px">
              <el-input
                v-model="associateServiceQueryParams.serviceName"
                placeholder="请输入事项名称"
                clearable
                size="small"
                @keyup.enter.native="handleAssociateServiceSearch"
                style="width: 300px; margin-right: 10px"
              />
              <el-input
                v-model="associateServiceQueryParams.deptName"
                placeholder="请输入实施部门"
                clearable
                size="small"
                @keyup.enter.native="handleAssociateServiceSearch"
                style="width: 300px; margin-right: 10px"
              />
              <el-button type="primary" icon="el-icon-search" size="small" @click="handleAssociateServiceSearch">搜索
              </el-button>
            </div>
            <el-table
              ref="associateServiceTable"
              max-height="500px"
              :data="associateServiceList"
              @selection-change="checkChang"
            >
              <el-table-column type="selection" width="55" align="center" :selectable="isCheck"/>
              <el-table-column label="事项编码" width="190" align="center" prop="serviceCode"/>
              <el-table-column label="事项名称" align="center" prop="serviceName"/>
              <el-table-column label="实施部门" align="center" prop="deptName"/>
            </el-table>
            <div class="pagination">
              <pagination
                v-show="associateServiceListTotal>0"
                :total="associateServiceListTotal"
                layout="total, prev, pager, next, jumper"
                :page.sync="associateServiceQueryParams.pageNum"
                :limit.sync="associateServiceQueryParams.pageSize"
                @pagination="handlePageChange"
              />
            </div>
            <div slot="footer" class="Allfooter">
              <el-button
                type="primary"
                @click="confirm">
                确 定
              </el-button>

              <el-button @click="closeAllMatterDialog">关 闭</el-button>
            </div>
          </div>
          <div class="div2" v-loading="divTwoLoading">
            <div style="margin: 20px 0 20px 20px">
              <el-input
                v-model="alreadyParams.serviceName"
                placeholder="请输入事项名称"
                clearable
                size="small"
                @keyup.enter.native="handlePageChange1"
                style="width: 300px; margin-right: 10px"
              />
              <el-input
                v-model="alreadyParams.deptName"
                placeholder="请输入实施部门"
                clearable
                size="small"
                @keyup.enter.native="handlePageChange1"
                style="width: 300px; margin-right: 10px"
              />
              <el-button type="primary" icon="el-icon-search" size="small" @click="handlePageChange1">搜索
              </el-button>
            </div>

            <el-table
              ref="associateServiceTable"
              max-height="500px"
              :data="alreadyArr"
            >
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="事项编码" width="190" align="center" prop="serviceRealCode"/>
              <el-table-column label="事项名称" align="center" prop="serviceName"/>
              <el-table-column label="实施部门" align="center" prop="deptName"/>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="alreadyDelete(scope.row)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination">
              <pagination
                v-show="alreadTotal>0"
                :total="alreadTotal"
                layout="total, prev, pager, next, jumper"
                :page.sync="alreadyParams.pageNum"
                :limit.sync="alreadyParams.pageSize"
                @pagination="handlePageChange1"
              />
            </div>
          </div>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listService,
  getService,
  delService,
  addService,
  updateService,
  listAssociateService,
  batchOutsideServices,
  unrelatedMatters,
  correlationAll,
  alreadyCorrelation,
  deleteAlready
} from "@/api/items/service";
import {
  getBaseStepList,
  stepBindService,
  getStepByService
} from "@/api/items/serviceSteps";

import MyTreeSelectorQuery from "@/views/components/myTreeSelectorQuery";
import {navTypeOptions, businessTypeOptions, loginAccountTypeOptions, printFooterOption} from '@/utils/dicts'
import UDraggableTransfer from './UDraggableTransfer'

export default {
  name: "affairBaseInfo",
  components: {MyTreeSelectorQuery, UDraggableTransfer},
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 事项表格数据
      itemsList: [],
      // 弹出层标题
      title: "",
      // 是否显示添加修改弹出层
      openEditDialog: false,
      // 是否显示关联事项弹出层
      openAssociateServiceDialog: false,
      // 是否显示全省通办关联弹出框
      openAllMatterDialog: false,
      //是否启用下拉选项 1是  2:否
      isEnableOptions: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 2
        }
      ],
      navTypeOptions,
      businessTypeOptions,
      loginAccountTypeOptions,
      printFooterOption,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceName: undefined,
        serviceCode: undefined,
        type: undefined,
        businessType: undefined,
        personType: undefined,
        stamp: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        serviceName: [
          {required: true, message: "事项名称不能为空", trigger: "blur"}
        ],
        itemType: [
          {required: true, message: "事项类型不能为空", trigger: "change"}
        ],
        serviceUrl: [
          // {required: true, message: "路由地址不能为空", trigger: "blur"}
        ],
        enable: [
          {required: true, message: "是否启用不能为空", trigger: "change"}
        ],
        type: [
          {required: true, message: "跳转类型不能为空", trigger: "change"}
        ],
        businessType: [
          {required: true, message: "业务类型不能为空", trigger: "change"}
        ],
      },
      // 详细信息弹窗
      openDetailInfoDialog: false,
      // 详细信息数据
      detailInfoForm: {},
      // 关联事项列表数据
      associateServiceList: [],
      // 查询参数
      associateServiceQueryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceName: undefined,
        serviceCode: undefined,
        deptName: undefined
      },
      // 关联事项列表总条数
      associateServiceListTotal: 0,
      // 当前页面选中的关联事项
      currentPageSelectedList: [],
      // 缓存已选中的关联事项
      cacheSelectedAssociateServices: [],
      // 关联事项弹窗加载中遮罩
      associateServiceDialogLoading: false,
      // 步骤选择列表
      stepsList: [],
      // 已选择的事项步骤id
      selectedStepIds: [],
      data1: [
        {serviceCode: "10202306261653460001", serviceName: "个人一件事", serviceType: "a类"},
        {serviceCode: "10202306261653460002", serviceName: "个人两件事", serviceType: "b类"},
        {serviceCode: "10202306261653460003", serviceName: "个人两件事", serviceType: "c类"},
        {serviceCode: "10202306261653460004", serviceName: "个人两件事", serviceType: "d类"},
      ],
      data2: this.$store.state.user.keepData,
      TransArr: [],
      AllMatterLoading: false,
      keepData: [],
      newArr1: [],
      correlationType: 0,
      ServiceParams: [],
      alreadyParams: {
        pageNum: 1,
        pageSize: 10,
        serviceName: '',
        serviceCode: '',
        deptName: '',
        deptCode: '',
        regionCode: ''
      },
      alreadyArr: [],
      alreadTotal: 0,
      divTwoLoading: false,
      proServiceCode: null,
      proServiceName: null
    };
  },
  computed: {
    // 已选中的事项需要填写的信息是否已经填写完整
    selectedAssociateServiceInfoIsValid() {
      // 判断是否有已勾选的事项，未填写完整信息
      for (let i = 0; i < this.currentPageSelectedList.length; i++) {
        const item = this.currentPageSelectedList[i];
        if (!item.icon || !item.serviceUrl) return false;
      }
      return true;
    },
    showStepConfig(){
      // 查询类事项和对接中台表单事项可动态配置步骤
      const types = [3, 4, 5, 6]
      return types.includes(this.form.type)
    },
    showServiceUrl(){
      // iframe事项、模块联邦引入事项、跳转自定义页面事项、跳转外部url事项才展示路由配置
      const types = [2, 8, 9, 11]
      return types.includes(this.form.type)
    }
  },
  methods: {
    isCheck(row) {
      return row.exerciseAreaCode !== "230000"
    },
    checkChang(item) {
      this.ServiceParams = item.map(val => {
        return {
          createBy: val.createBy,
          createTime: val.createTime,
          deptCode: val.deptCode,
          deptName: val.deptName,
          id: val.id,
          parentRegionCode: val.parentRegionCode,
          regionCode: val.exerciseAreaCode,
          remar: val.remar,
          serviceRealCode: val.serviceCode,
          serviceName: val.serviceName,
          status: val.status,
          updateBy: val.up,
          updateTime: val.updateTime,
          serviceCode: this.proServiceCode
        }
      })
    },
    confirm() {
      this.$confirm('您确定要关联这些事项吗',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        correlationAll(this.ServiceParams).then(res => {
          this.getAssociateServiceList()
          this.alreadyParams.pageNum = 1
          this.getAlreadyCorrelation()
        })
      })
    },
    getAlreadyCorrelation() {
      this.divTwoLoading = true
      // this.alreadyParams.pageNum = 1
      this.alreadyParams.serviceCode = this.proServiceCode
      alreadyCorrelation(this.alreadyParams).then(res => {
        this.divTwoLoading = false
        this.alreadyArr = res.rows
        this.alreadTotal = res.total
      })
    },
    handlePageChange1() {
      this.getAlreadyCorrelation()
    },
    alreadyDelete(row) {
      this.$confirm('您确定要删除关联这个事项吗',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        deleteAlready(row.id).then(() => {
          this.getAlreadyCorrelation()
        })
      })
    },
    // 设置事项步骤关联
    setServiceStep(serviceCode) {
      const stepSort = this.selectedStepIds.map((item, index) => {
        return {sort: index + 1, stepId: item}
      })
      stepBindService({
        serviceCode,
        stepSort: stepSort
      }).then(response => {
        // console.log('设置事项关联步骤成功', response)
      })
    },
    /** 查询可配置步骤列表 */
    getStepsList() {
      getBaseStepList({
        pageNum: 1,
        pageSize: 100000
      }).then(response => {
        this.stepsList = response.rows;
      })
    },
    // 设置办理事项标准步骤
    setServiceStandardStep() {
      // 基本办理步骤列表
      const componentsName = [
        {sort: 1, componentName: "ConfirmServiceInfo", stepName: '信息确认'},
        {sort: 2, componentName: "ConfirmWork", stepName: '确认办事情形'},
        {sort: 3, componentName: "CheckInformation", stepName: '核对办事资料'},
        {sort: 4, componentName: "FillForm", stepName: '填写表单'},
        {sort: 5, componentName: "UploadInformation", stepName: '上传资料'},
        {sort: 6, componentName: "CheckSignature", stepName: '电子签名'},
        {sort: 7, componentName: "ResultGetWay", stepName: '选择结果获取方式'},
        {sort: 8, componentName: "SubmitResultView", stepName: '提交完成'}
        // 暂时没用到好差评
        // {sort: 4, componentName: "EvaluateView", stepName: '服务好差评'}
      ]
      this.selectedStepIds = componentsName.map((item1, index) => {
        const tag = this.stepsList.find(item2 => item1.componentName === item2.componentName) || {}
        return tag.id
      })
      // 自动勾选步骤
      this.$refs.draggable.autoSelectedSteps(this.selectedStepIds)
    },
    // 事项类型改变，如果选择的是办理事项事项步骤默认配置为标准步骤
    handleServiceTypeChange(value) {
      // 切换事项类型清空登录账号类型
      this.form.personType = undefined
      this.form.stamp = undefined
      if (value === 5 || value === 6) { // 自动勾选办理事项默认标准步骤
        this.setServiceStandardStep()
      }  else { // 清空步骤
        this.selectedStepIds = []
        this.$refs.draggable.autoSelectedSteps(this.selectedStepIds)
      }
    },
    // 业务类型改变
    handleBusinessTypeChange(value){
      this.form.remark = this.queryDictLabel(this.businessTypeOptions, value) ?.slice(0, -1) || ''
    },
    // 复制图片url
    copyImageUrl(url) {
      this.$copyText(url).then(message => {
        this.$modal.msgSuccess({
          message: '复制成功',
        })
      }).catch(err => {
        this.$modal.msgError({
          message: '复制失败',
        })
      })
    },
    imageUploadSuccess(imgUrl) {
      this.form.icon = imgUrl;
    },
    // 关联事项弹窗分页页数改变
    handlePageChange() {
      // 缓存已选中事项信息
      this.saveSelectedItemToCacheList();
      this.getAssociateServiceList();
    },

    // 提示已选中关联事项哪一行信息没有补充完整
    showRowInfoIncompleteTip(btnText) {
      // const rows = [];
      // // 检查已选中事项图标和路由地址是否有填写
      // for (let i = 0; i < this.currentPageSelectedList.length; i++) {
      //   const item = this.currentPageSelectedList[i]
      //   console.log(111, item)
      //   if (!item.icon || item.type == 2 && !item.serviceUrl) {
      //     rows.push(i + 1);
      //   }
      // }
      //
      // if (rows.length) {
      //   this.$alert(
      //     `请把已勾选第${rows.join("、")}行事项信息补充完整再进行${btnText}！`,
      //     '提示', {
      //       confirmButtonText: '确定',
      //       type: 'warning'
      //     });
      //   return false;
      // }
      return true;
    },

    // 关联事项弹窗搜索按钮
    handleAssociateServiceSearch() {
      this.associateServiceQueryParams.pageNum = 1
      // 缓存已选中事项信息
      this.saveSelectedItemToCacheList();
      // 获取列表
      this.getAssociateServiceList();
    },

    // 获取关联事项列表
    getAssociateServiceList() {
      // 显示加载中
      this.associateServiceDialogLoading = true;
      this.AllMatterLoading = true

      // 调用接口获取同步事项数据
      unrelatedMatters(this.associateServiceQueryParams).then(response => {
        if (!response.data.tCfgServicesList) {
          response.data.tCfgServicesList = []
          response.data.total = 0
        }
        this.associateServiceDialogLoading = false;
        this.AllMatterLoading = false
        this.associateServiceList = response.data.tCfgServicesList.map(item => {
          // 判断是否存在缓存里面，如果存在使用缓存里面的数据进行回填信息
          const cacheItem = this.cacheSelectedAssociateServices.find(cacheItem => {
            return cacheItem.serviceCode === item.serviceCode
          })
          if (cacheItem) return cacheItem;
          return {
            ...item,
            icon: '',
            serviceUrl: '',
            // 默认办理类事项
            type: 5,
            businessType: 1,
            enable: 1,
          }
        });
        this.data1 = this.associateServiceList
        this.associateServiceListTotal = response.data.total;
        // 设置表格多选框默认选中
        this.$nextTick(() => {
          for (let i = 0; i < this.associateServiceList.length; i++) {
            const row = this.associateServiceList[i];
            if (this.cacheSelectedAssociateServices.some(item => row.serviceCode === item.serviceCode)) {
              this.$refs.associateServiceTable.toggleRowSelection(row);
            }
          }
        })
      });
    },
    // 确定关联事项
    handleConfirmAssociateService() {

      // 检查当前页选中数据是否有填写完整
      const checkSelectedServiceIsFull = this.showRowInfoIncompleteTip('关联');

      // 如果当前页选中事项信息已补充完整，将当前加入缓存
      if (checkSelectedServiceIsFull) {
        // 将当前选中项保存到缓存选中列表
        this.saveSelectedItemToCacheList(false);
        // 如果检查通过并且在缓存中有选中事项,显示下一步选择关联网点
        if (!this.cacheSelectedAssociateServices.length) {
          return this.$alert(
            `请勾选要关联的事项！`,
            '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            });
        }

        this.$confirm(`是否确定将已选中的${this.cacheSelectedAssociateServices.length}个事项关联？`,
          '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
          batchOutsideServices({
            services: this.cacheSelectedAssociateServices
          }).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.openAssociateServiceDialog = false;
            // 清空缓存当前页选中的数据
            this.currentPageSelectedList = [];
            this.getList();
          });
        }).catch(() => {

        });
      }
    },

    // 关闭关联事项弹窗回调
    closeAssociateServiceDialogCallback() {
      // 关闭弹窗后清空选中缓存列表和选中列表
      this.cacheSelectedAssociateServices = [];
      this.currentPageSelectedList = [];
      this.associateServiceList = [];
      this.data1 = [];
    },

    // 将选中项推入缓存列表，未选中的从缓存列表删除
    saveSelectedItemToCacheList(needClearCurrentPage = true) {
      // 保存当前页所有rowguids
      const currentPageIds = this.associateServiceList.map(item => item.serviceCode);

      // 将当前页数据从缓存中删除，再将已选中的加入到缓存
      this.cacheSelectedAssociateServices = this.cacheSelectedAssociateServices.filter(item => {
        return !currentPageIds.includes(item.serviceCode)
      }).concat(this.currentPageSelectedList);
      // 清空当前页的选中数据

      if (needClearCurrentPage) this.currentPageSelectedList = [];
    },

    // 关联事项弹窗多选框选择改变
    handleAssociateServiceSelectionChange(selection) {
      // 当前页选中列表
      this.currentPageSelectedList = selection;
    },
    /* 根据值查询选项文本
    @param {Array} originData 字典数据源
    @param {String/Array} value 值
    */
    queryDictLabel(originData, value) {
      const item = originData.find(item => {
        return item.value == value
      })
      return item ? item.label : null
    },

    /** 详细按钮操作 */
    handleView(row) {
      this.openDetailInfoDialog = true;
      this.detailInfoForm = row;
    },
    // 从别的页面跳转过来查看事项详情 自动回填筛选条件事项编码
    autoFillServiceCode(serviceCode) {
      if (serviceCode) this.queryParams.serviceCode = serviceCode;
      this.getList();
    },

    /** 查询事项列表 */
    getList() {
      this.loading = true;
      listService(this.queryParams).then(response => {
        this.itemsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.openEditDialog = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serviceCode: null,
        serviceName: null,
        serviceAbstract: null,
        serviceUrl: null,
        deptName: null,
        icon: null,
        enable: 1,
        type: null,
        personType: null,
        serviceParam: null,
        businessType: null,
        stamp: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.serviceCode = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.openEditDialog = true;
      this.title = "添加事项";
    },
    // 关联事项
    handleAssociateService() {
      this.openAssociateServiceDialog = true;
      console.log(1065, this.associateServiceList)
      // 重置为第一页
      this.associateServiceQueryParams.deptName = undefined;
      this.associateServiceQueryParams.serviceName = undefined;
      this.associateServiceQueryParams.pageNum = 1;
      this.getAssociateServiceList();
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0]
      const itemInfo = this.itemsList.find(item => {
        return item.id === id
      })
      await getService(id).then(response => {
        this.form = response.data;
        this.title = "修改事项";
        this.openEditDialog = true;
      });

      // 获取已配置步骤
      getStepByService({serviceId: itemInfo.serviceCode}).then(response => {
        // 已选择的事项步骤id
        this.selectedStepIds = response.data.map(item => item.id);
        // 自动勾选已选步骤
        this.$refs.draggable.autoSelectedSteps(this.selectedStepIds)
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateService(this.form).then(response => {
              // 设置事项步骤
              this.setServiceStep(this.form.serviceCode)
              this.$modal.msgSuccess("修改成功");
              this.openEditDialog = false;
              this.getList();
            });
          } else {
            addService(this.form).then(response => {
              // 设置事项步骤
              this.setServiceStep(response.data.serviceCode)
              this.$modal.msgSuccess("新增成功");
              this.openEditDialog = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除事项？').then(function () {
        return delService(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        // this.disassociate()
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      this.download('items/service/export', {
        ...this.queryParams
      }, `事项管理_${currentDate}.xlsx`)
    },
    // 关联事项
    getMatterType(item) {
      if (item.row.type === 12) {
        this.openAllMatterDialog = true
        this.proServiceCode = item.row.serviceCode
        this.proServiceName = item.row.serviceName
        this.associateServiceQueryParams.serviceName = undefined
        this.associateServiceQueryParams.deptName = undefined
        this.alreadyParams.serviceName = undefined
        this.alreadyParams.deptName = undefined
        this.associateServiceQueryParams.pageNum = 1
        this.getAssociateServiceList()
        this.getAlreadyCorrelation()
      }
    },
    closeAllMatterDialog() {
      this.openAllMatterDialog = false
    }
  },
  created() {
    this.getList()
    this.getStepsList()
  },
  watch: {
    // 修改、编辑事项信息弹窗
    openEditDialog(newValue) {
      if (newValue) {
        // 打开弹窗时：获取可配置步骤列表
        this.getStepsList()
      } else {
        // 关闭时：清空已选步骤列表
        this.selectedStepIds = []
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.affairBaseInfo {
  width: 100%;
  height: 100%;

  .right-wrap {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .left-wrap {
    box-sizing: border-box;
    width: 240px;
    height: inherit;
    min-width: 250px;
    margin-left: -5px;
    padding: 10px;
    margin-right: 15px;
    border: 1px solid #dfe4ed;
    border-radius: 4px;

    .title {
      margin-bottom: 10px;
      font-size: 14px;
      color: #606266;
      font-weight: bold;
    }

    .tree-wrap {
      width: 100%;
      height: inherit;
      overflow-y: auto;
    }
  }

}

::v-deep .el-select {
  width: 100%;
}

.dialog-footer {
  position: relative;

  .tip {
    position: absolute;
    left: 0;
    top: 0;
    font-size: 16px;
    line-height: 36px;
    color: red;
  }
}

.select-branch {
  .title {
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: bold;

    &:before {
      content: "*";
      color: #ff4949;
      margin-right: 4px;
    }
  }
}

.pagination {
  position: relative;

  .clickMask {
    z-index: 1;
    position: absolute;
    width: 600px;
    height: 100%;
    top: 0;
    right: 0;
    background: red;
    opacity: 0;
  }
}

.dialog-content {
  box-sizing: border-box;
  max-height: 70vh;
  padding-right: 20px;
  overflow-y: auto;
}
.Allfooter {
  display: flex;
  justify-content: center;
  align-items: center;
  //margin-right: 30px;
}
::v-deep .el-transfer-panel {
  width: 500px;
  height: 450px;
}
::v-deep .el-transfer-panel__list.is-filterable {
  height: 310px;
}
.bigDiv {
  display: flex;
}
.div1 {
  flex-grow: 0;
  width: 600px;
}
.div2{
  flex-grow: 0;
  width: 600px;
  margin-left: 50px;
}
.provinceWide:hover {
  color: skyblue;
  cursor: pointer;
}
</style>
